import base64
import json
import pickle

from django import http
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection

# from League_of_Legends.utils import constants


from apps.goods.models import Goods
from utils import constants
from utils.response_code import RETCODE


class DeleteCart(View):
    def post(self, request):
        """删除购物车"""
        print('进入post请求了哦')
        # 获取商品id
        sku_id = request.POST.get('sku_id')
        print(sku_id, 'sku_id')
        # 校验参数
        try:
            sku = Goods.objects.get(id=sku_id)
        except Goods.DoesNotExist:
            return http.HttpResponseBadRequest('sku is not ')

        # 判断用户是否登录
        user = request.user
        if user.is_authenticated:
            # 1连接redis数据
            redis_con = get_redis_connection('carts')
            # 2创建管道
            pl = redis_con.pipeline()
            # 3删除购物车数据
            pl.hdel('carts_%s' % user.id, sku_id)
            pl.srem('selected_%s' % user.id, sku_id)
            # 4执行管道
            pl.execute()
            # 5返回响应
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '删除购物车成功'})
        else:
            # 1取出cookie
            cart_str = request.COOKIES.get('carts')
            # 2判断cookie是否存在 存在就解密 不存在就定义为空字典
            if cart_str:
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                cart_dict = {}
            response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': '删除购物车成功'})
            # 3如果用户删除的在字典中 就del删除它
            if sku_id in cart_dict:
                del cart_dict[sku_id]
                # 对字典进行加密
                cookie_cart_dict = base64.b64encode(pickle.dumps(cart_dict)).decode()
                # 设置cookie
                response.set_cookie('carts', cookie_cart_dict, max_age=constants.CARTS_COOKIE_EXPIRES)
            return response
